from selenium import webdriver
from selenium.webdriver.support.events import EventFiringWebDriver, AbstractEventListener
from selenium.webdriver.common.by import By
import time


# 定义事件监听器
class MyListener(AbstractEventListener):
    def before_navigate_to(self, url, driver):
        print(f"正在打开页面：{url}")

    def after_navigate_to(self, url, driver):
        print(f"页面已打开：{url}")

    def before_click(self, element, driver):
        print(f"正在点击元素：{element.text}")

    def after_click(self, element, driver):
        print(f"已点击元素：{element.text}")


# 初始化Chrome浏览器
driver = webdriver.Chrome()

# 包装浏览器对象，添加事件监听器
ef_driver = EventFiringWebDriver(driver, MyListener())

try:
    # 打开百度页面
    ef_driver.get("https://www.baidu.com")

    # 查找搜索框并输入文本
    search_box = ef_driver.find_element(By.ID, "kw")
    search_box.send_keys("hello world")

    # 点击搜索按钮
    search_button = ef_driver.find_element(By.ID, "su")
    search_button.click()

    # 等待几秒观察结果
    time.sleep(3)

    # 截图保存
    ef_driver.save_screenshot("baidu_search.png")
    print("截图已保存")

except Exception as e:
    print(f"操作失败：{e}")

finally:
    # 关闭浏览器
    ef_driver.quit()